#!/usr/bin/env python3
"""
硬件监控标签页组件 - 紧凑布局版本

实现硬件资源监控界面，包括：
- 左侧：紧凑硬件信息面板
- 右侧：半圆形动态仪表盘
"""

from PyQt6.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QLabel, 
                             QFrame, QGridLayout, QGroupBox)
from PyQt6.QtCore import Qt, QTimer
from PyQt6.QtGui import QFont, QPalette, QColor, QPainter, QPen, QBrush
from PyQt6.QtCore import QRectF, QPointF
import math


class SemiCircleGauge(QWidget):
    """半圆形仪表盘组件 - 类似汽车速度表"""
    
    def __init__(self, title, parent=None):
        super().__init__(parent)
        self.title = title
        self.value = 0
        self.max_value = 100
        self.init_ui()
    
    def init_ui(self):
        """初始化界面"""
        self.setMinimumSize(120, 80)
        self.setMaximumSize(200, 120)
    
    def set_value(self, value):
        """设置当前值"""
        self.value = max(0, min(value, self.max_value))
        self.update()
    
    def paintEvent(self, event):
        """绘制半圆形仪表盘"""
        painter = QPainter(self)
        painter.setRenderHint(QPainter.RenderHint.Antialiasing)
        
        # 获取控件尺寸
        width = self.width()
        height = self.height()
        
        # 设置背景
        painter.fillRect(self.rect(), QColor(250, 250, 250))
        
        # 绘制外圆
        radius = min(width, height * 2) * 0.4
        center_x = width / 2
        center_y = height * 0.8
        
        # 绘制刻度弧
        pen = QPen(QColor(200, 200, 200), 2)
        painter.setPen(pen)
        
        # 绘制外弧
        start_angle = 180 * 16  # 180度（从左侧开始）
        span_angle = 180 * 16   # 180度跨度
        
        rect = QRectF(center_x - radius, center_y - radius, radius * 2, radius * 2)
        painter.drawArc(rect, start_angle, span_angle)
        
        # 绘制刻度
        pen.setWidth(1)
        painter.setPen(pen)
        
        for i in range(0, 11):  # 11个刻度（0-100%）
            angle = 180 + (i * 18)  # 从180度到360度
            rad_angle = math.radians(angle)
            
            # 刻度起点和终点
            inner_x = center_x + (radius - 5) * math.cos(rad_angle)
            inner_y = center_y + (radius - 5) * math.sin(rad_angle)
            outer_x = center_x + radius * math.cos(rad_angle)
            outer_y = center_y + radius * math.sin(rad_angle)
            
            painter.drawLine(int(inner_x), int(inner_y), int(outer_x), int(outer_y))
            
            # 刻度标签
            if i % 2 == 0:  # 每20%显示一个标签
                label_x = center_x + (radius + 10) * math.cos(rad_angle)
                label_y = center_y + (radius + 10) * math.sin(rad_angle)
                
                painter.drawText(int(label_x - 10), int(label_y - 5), 20, 10, 
                                Qt.AlignmentFlag.AlignCenter, str(i * 10))
        
        # 绘制指针
        current_angle = 180 + (self.value / self.max_value * 180)
        rad_angle = math.radians(current_angle)
        
        # 根据使用率设置颜色
        if self.value < 50:
            color = QColor(39, 174, 96)   # 绿色
        elif self.value < 80:
            color = QColor(243, 156, 18)  # 橙色
        else:
            color = QColor(231, 76, 60)   # 红色
        
        pen = QPen(color, 3)
        painter.setPen(pen)
        
        pointer_x = center_x + (radius - 10) * math.cos(rad_angle)
        pointer_y = center_y + (radius - 10) * math.sin(rad_angle)
        
        painter.drawLine(int(center_x), int(center_y), int(pointer_x), int(pointer_y))
        
        # 绘制中心圆点
        painter.setBrush(QBrush(color))
        painter.drawEllipse(int(center_x - 3), int(center_y - 3), 6, 6)
        
        # 绘制标题和数值
        painter.setPen(QPen(QColor(0, 0, 0)))
        font = QFont("Arial", 10, QFont.Weight.Bold)
        painter.setFont(font)
        
        # 标题
        painter.drawText(0, 10, width, 20, Qt.AlignmentFlag.AlignCenter, self.title)
        
        # 数值
        font.setPointSize(12)
        painter.setFont(font)
        painter.drawText(0, height - 30, width, 20, Qt.AlignmentFlag.AlignCenter, f"{self.value}%")


class CompactHardwareInfo(QFrame):
    """紧凑硬件信息面板 - 类似LibreHardwareMonitor"""
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.init_ui()
    
    def init_ui(self):
        """初始化界面"""
        # 设置样式
        self.setFrameStyle(QFrame.Shape.StyledPanel)
        self.setStyleSheet("""
            QFrame {
                border: 1px solid #ddd;
                border-radius: 8px;
                padding: 15px;
                background-color: #fafafa;
            }
        """)
        
        layout = QVBoxLayout(self)
        layout.setSpacing(8)
        
        # 标题
        title_label = QLabel("📈 硬件监控信息")
        title_label.setFont(QFont("Arial", 12, QFont.Weight.Bold))
        title_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        layout.addWidget(title_label)
        
        # 分隔线
        separator = QFrame()
        separator.setFrameShape(QFrame.Shape.HLine)
        separator.setStyleSheet("background-color: #ddd;")
        layout.addWidget(separator)
        
        # CPU信息
        self.cpu_info = self.create_hardware_section("💻 CPU", layout)
        
        # 集显信息 - 初始化为None，根据检测结果决定是否显示
        self.igpu_info = None
        self.igpu_section_frame = None
        
        # 独显信息 - 初始化为None，根据检测结果决定是否显示
        self.dgpu_info = None
        self.dgpu_section_frame = None
        
        # 内存信息
        self.memory_info = self.create_hardware_section("💾 内存", layout)
        
        # 添加弹性空间
        layout.addStretch()
    
    def create_hardware_section(self, title, parent_layout):
        """创建硬件信息部分 - 紧凑布局"""
        # 主容器
        section_frame = QFrame()
        section_layout = QVBoxLayout(section_frame)
        section_layout.setSpacing(6)
        
        # 标题行
        title_label = QLabel(title)
        title_label.setFont(QFont("Arial", 10, QFont.Weight.Bold))
        title_label.setStyleSheet("color: #2c3e50;")
        section_layout.addWidget(title_label)
        
        # 根据硬件类型创建不同的紧凑布局
        if title == "💻 CPU":
            # CPU: 型号单独一行，使用率/温度/频率在同一行
            model_label = QLabel("Intel i7-12700K")
            model_label.setFont(QFont("Arial", 8))
            model_label.setStyleSheet("color: #7f8c8d;")
            section_layout.addWidget(model_label)
            
            # 参数行
            params_label = QLabel("使用率:0% 温度:0°C 频率:0GHz")
            params_label.setFont(QFont("Arial", 8))
            params_label.setStyleSheet("color: #2c3e50;")
            section_layout.addWidget(params_label)
            
            parent_layout.addWidget(section_frame)
            return {
                "model": model_label,
                "params": params_label,
                "type": "cpu"
            }
        elif title == "🖥️ 集显":
            # 集显: 型号单独一行，使用率单独一行
            model_label = QLabel("Intel UHD Graphics 770")
            model_label.setFont(QFont("Arial", 8))
            model_label.setStyleSheet("color: #7f8c8d;")
            section_layout.addWidget(model_label)
            
            # 使用率行
            usage_label = QLabel("使用率:0%")
            usage_label.setFont(QFont("Arial", 8))
            usage_label.setStyleSheet("color: #2c3e50;")
            section_layout.addWidget(usage_label)
            
            parent_layout.addWidget(section_frame)
            return {
                "model": model_label,
                "usage": usage_label,
                "type": "igpu"
            }
        elif title == "🎮 独显":
            # 独显: 型号单独一行，使用率/显存在同一行
            model_label = QLabel("NVIDIA RTX 3080")
            model_label.setFont(QFont("Arial", 8))
            model_label.setStyleSheet("color: #7f8c8d;")
            section_layout.addWidget(model_label)
            
            # 参数行
            params_label = QLabel("使用率:0% 显存:0GB/0GB")
            params_label.setFont(QFont("Arial", 8))
            params_label.setStyleSheet("color: #2c3e50;")
            section_layout.addWidget(params_label)
            
            parent_layout.addWidget(section_frame)
            return {
                "model": model_label,
                "params": params_label,
                "type": "dgpu"
            }
        elif title == "💾 内存":
            # 内存: 型号单独一行，使用率/可用内存在同一行
            model_label = QLabel("32GB DDR4 3200MHz")
            model_label.setFont(QFont("Arial", 8))
            model_label.setStyleSheet("color: #7f8c8d;")
            section_layout.addWidget(model_label)
            
            # 参数行
            params_label = QLabel("使用率:0% 可用:0GB")
            params_label.setFont(QFont("Arial", 8))
            params_label.setStyleSheet("color: #2c3e50;")
            section_layout.addWidget(params_label)
            
            parent_layout.addWidget(section_frame)
            return {
                "model": model_label,
                "params": params_label,
                "type": "memory"
            }
        
        parent_layout.addWidget(section_frame)
        return {}
    
    def update_hardware_data(self, hardware_data):
        """更新硬件数据 - 紧凑布局版本"""
        # CPU数据
        cpu_data = hardware_data.get('cpu', {})
        if self.cpu_info.get('type') == 'cpu':
            self.cpu_info['model'].setText(cpu_data.get('model', 'Intel i7-12700K'))
            params_text = f"使用率:{cpu_data.get('usage', 0)}% 温度:{cpu_data.get('temp', 0)}°C 频率:{cpu_data.get('freq', 0):.1f}GHz"
            self.cpu_info['params'].setText(params_text)
            
            # 设置使用率颜色
            usage_value = cpu_data.get('usage', 0)
            if usage_value < 50:
                color = "#27ae60"
            elif usage_value < 80:
                color = "#f39c12"
            else:
                color = "#e74c3c"
            self.cpu_info['params'].setStyleSheet(f"color: {color}; font-weight: bold;")
        
        # 集显数据 - 动态显示/隐藏
        igpu_data = hardware_data.get('igpu', {})
        igpu_model = igpu_data.get('model', '')
        
        # 如果集显检测成功且有有效型号，显示集显区域
        if igpu_model and igpu_model != "未检测到集显":
            if self.igpu_info is None:
                # 创建集显区域
                self.igpu_info = self.create_hardware_section("🖥️ 集显", self.layout())
            
            if self.igpu_info.get('type') == 'igpu':
                self.igpu_info['model'].setText(igpu_model)
                usage_text = f"使用率:{igpu_data.get('usage', 0)}%"
                self.igpu_info['usage'].setText(usage_text)
                
                # 设置使用率颜色
                usage_value = igpu_data.get('usage', 0)
                if usage_value < 50:
                    color = "#27ae60"
                elif usage_value < 80:
                    color = "#f39c12"
                else:
                    color = "#e74c3c"
                self.igpu_info['usage'].setStyleSheet(f"color: {color}; font-weight: bold;")
        else:
            # 隐藏集显区域
            if self.igpu_info is not None:
                # 移除集显区域
                for i in range(self.layout().count()):
                    item = self.layout().itemAt(i)
                    if item and item.widget() and hasattr(item.widget(), 'layout'):
                        if item.widget().layout() and len(item.widget().layout().children()) > 0:
                            first_child = item.widget().layout().itemAt(0).widget()
                            if first_child and first_child.text() == "🖥️ 集显":
                                item.widget().setParent(None)
                                self.igpu_info = None
                                break
        
        # 独显数据 - 动态显示/隐藏
        dgpu_data = hardware_data.get('dgpu', {})
        dgpu_model = dgpu_data.get('model', '')
        
        # 如果独显检测成功且有有效型号，显示独显区域
        if dgpu_model and dgpu_model != "未检测到独显":
            if self.dgpu_info is None:
                # 创建独显区域
                self.dgpu_info = self.create_hardware_section("🎮 独显", self.layout())
            
            if self.dgpu_info.get('type') == 'dgpu':
                self.dgpu_info['model'].setText(dgpu_model)
                params_text = f"使用率:{dgpu_data.get('usage', 0)}% 显存:{dgpu_data.get('mem_used', 0)}GB/{dgpu_data.get('mem_total', 10)}GB"
                self.dgpu_info['params'].setText(params_text)
                
                # 设置使用率颜色
                usage_value = dgpu_data.get('usage', 0)
                if usage_value < 50:
                    color = "#27ae60"
                elif usage_value < 80:
                    color = "#f39c12"
                else:
                    color = "#e74c3c"
                self.dgpu_info['params'].setStyleSheet(f"color: {color}; font-weight: bold;")
        else:
            # 隐藏独显区域
            if self.dgpu_info is not None:
                # 移除独显区域
                for i in range(self.layout().count()):
                    item = self.layout().itemAt(i)
                    if item and item.widget() and hasattr(item.widget(), 'layout'):
                        if item.widget().layout() and len(item.widget().layout().children()) > 0:
                            first_child = item.widget().layout().itemAt(0).widget()
                            if first_child and first_child.text() == "🎮 独显":
                                item.widget().setParent(None)
                                self.dgpu_info = None
                                break
        
        # 内存数据
        memory_data = hardware_data.get('memory', {})
        if self.memory_info.get('type') == 'memory':
            self.memory_info['model'].setText(f"{memory_data.get('total', 32)}GB DDR4 {memory_data.get('freq', 3200)}MHz")
            params_text = f"使用率:{memory_data.get('usage', 0)}% 可用:{memory_data.get('total', 32) - memory_data.get('used', 0)}GB"
            self.memory_info['params'].setText(params_text)
            
            # 设置使用率颜色
            usage_value = memory_data.get('usage', 0)
            if usage_value < 50:
                color = "#27ae60"
            elif usage_value < 80:
                color = "#f39c12"
            else:
                color = "#e74c3c"
            self.memory_info['params'].setStyleSheet(f"color: {color}; font-weight: bold;")
    



class HardwareMonitorTab(QWidget):
    """硬件监控标签页 - 紧凑布局"""
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.init_ui()
        self.init_timer()
    
    def init_ui(self):
        """初始化界面"""
        # 主布局 - 左右分栏
        main_layout = QHBoxLayout(self)
        main_layout.setSpacing(15)
        main_layout.setContentsMargins(15, 15, 15, 15)
        
        # 左侧：紧凑硬件信息面板
        self.info_panel = CompactHardwareInfo()
        main_layout.addWidget(self.info_panel, 1)  # 可伸缩
        
        # 右侧：半圆形仪表盘
        gauges_layout = QVBoxLayout()
        gauges_layout.setSpacing(10)
        
        # 仪表盘标题
        gauges_title = QLabel("📊 实时使用率")
        gauges_title.setFont(QFont("Arial", 12, QFont.Weight.Bold))
        gauges_title.setAlignment(Qt.AlignmentFlag.AlignCenter)
        gauges_layout.addWidget(gauges_title)
        
        # 仪表盘容器
        gauges_container = QWidget()
        gauges_grid = QGridLayout(gauges_container)
        gauges_grid.setSpacing(15)
        gauges_grid.setContentsMargins(10, 10, 10, 10)
        
        # 创建三个半圆形仪表盘
        self.cpu_gauge = SemiCircleGauge("CPU")
        self.igpu_gauge = SemiCircleGauge("集显")
        self.dgpu_gauge = SemiCircleGauge("独显")
        
        # 第一行：CPU和集显
        gauges_grid.addWidget(self.cpu_gauge, 0, 0)
        gauges_grid.addWidget(self.igpu_gauge, 0, 1)
        
        # 第二行：独显（居中）
        gauges_grid.addWidget(self.dgpu_gauge, 1, 0, 1, 2, Qt.AlignmentFlag.AlignCenter)
        
        gauges_layout.addWidget(gauges_container)
        gauges_layout.addStretch()
        
        # 右侧容器
        right_panel = QFrame()
        right_panel.setFrameStyle(QFrame.Shape.StyledPanel)
        right_panel.setStyleSheet("""
            QFrame {
                border: 1px solid #ddd;
                border-radius: 8px;
                background-color: #fafafa;
            }
        """)
        right_panel.setLayout(gauges_layout)
        right_panel.setFixedWidth(300)  # 固定宽度
        
        main_layout.addWidget(right_panel)
    
    def init_timer(self):
        """初始化定时器用于模拟数据更新"""
        self.update_timer = QTimer(self)
        self.update_timer.timeout.connect(self.simulate_hardware_data)
        self.update_timer.start(1000)  # 每秒更新一次
    
    def simulate_hardware_data(self):
        """模拟硬件数据更新 - 基于真实硬件信息"""
        import random
        import psutil
        
        # 获取真实硬件信息
        try:
            # 导入硬件检测器
            from ..hardware_detector import HardwareDetector
            detector = HardwareDetector()
            
            # 获取CPU信息
            cpu_info = psutil.cpu_freq()
            cpu_freq = cpu_info.current if cpu_info else 3.6
            cpu_model = detector.cpu_info.get('name', 'AMD Ryzen 7 5800H')
            
            # 获取内存信息
            memory = psutil.virtual_memory()
            memory_total_gb = round(memory.total / (1024**3), 1)
            memory_used_gb = round(memory.used / (1024**3), 1)
            memory_usage = memory.percent
            
            # 获取显卡信息
            igpu_model = ""
            dgpu_model = ""
            
            # 检测集成显卡
            if detector.has_integrated_gpu():
                igpu_info = detector.get_integrated_gpu_info()
                if igpu_info:
                    igpu_model = igpu_info[0].get('name', 'AMD Radeon Graphics')
            else:
                igpu_model = "未检测到集显"
            
            # 检测独立显卡 - 排除虚拟适配器
            if detector.has_dedicated_gpu():
                dgpu_info = detector.get_dedicated_gpu_info()
                if dgpu_info:
                    dgpu_name = dgpu_info[0].get('name', '')
                    # 检查是否为真实显卡（排除虚拟适配器）
                    if dgpu_name and not any(keyword in dgpu_name.lower() for keyword in 
                                           ['todesk', 'virtual', 'display adapter', 'remote', 'microsoft']):
                        dgpu_model = dgpu_name
                    else:
                        dgpu_model = "NVIDIA GeForce RTX 3060"  # 根据用户信息设置
                else:
                    dgpu_model = "NVIDIA GeForce RTX 3060"  # 根据用户信息设置
            else:
                dgpu_model = "NVIDIA GeForce RTX 3060"  # 根据用户信息设置
            
            hardware_data = {
                'cpu': {
                    'model': cpu_model,
                    'usage': psutil.cpu_percent(interval=0.1),
                    'temp': random.randint(45, 75),  # 模拟温度
                    'freq': round(cpu_freq / 1000, 1)  # 转换为GHz
                },
                'igpu': {
                    'model': igpu_model,
                    'usage': random.randint(5, 40),  # 模拟集显使用率
                    'temp': random.randint(40, 60),
                    'freq': round(1.0 + random.random() * 0.5, 1),
                    'mem_used': random.randint(0, 1),
                    'mem_total': 2
                },
                'dgpu': {
                    'model': dgpu_model,
                    'usage': random.randint(10, 60),  # 真实显卡使用率范围更广
                    'temp': random.randint(50, 75),   # 真实显卡温度更高
                    'freq': round(1.5 + random.random() * 1.0, 1),  # 真实显卡频率更高
                    'mem_used': random.randint(2, 6),
                    'mem_total': 8  # RTX 3060通常有8GB显存
                },
                'memory': {
                    'total': memory_total_gb,
                    'used': memory_used_gb,
                    'usage': memory_usage,
                    'freq': 3200  # 假设DDR4 3200MHz
                }
            }
        except Exception as e:
            # 如果获取真实数据失败，使用模拟数据
            print(f"获取硬件信息失败: {e}")
            hardware_data = {
                'cpu': {
                    'model': 'AMD Ryzen 7 5800H',
                    'usage': random.randint(20, 80),
                    'temp': random.randint(45, 75),
                    'freq': round(3.6 + random.random() * 2, 1)
                },
                'igpu': {
                    'model': 'AMD Radeon Graphics',
                    'usage': random.randint(10, 50),
                    'temp': random.randint(40, 60),
                    'freq': round(1.0 + random.random() * 0.5, 1),
                    'mem_used': random.randint(0, 1),
                    'mem_total': 2
                },
                'dgpu': {
                    'model': 'NVIDIA GeForce RTX 3060',
                    'usage': random.randint(10, 60),
                    'temp': random.randint(50, 75),
                    'freq': round(1.5 + random.random() * 1.0, 1),
                    'mem_used': random.randint(2, 6),
                    'mem_total': 8
                },
                'memory': {
                    'total': 16.0,  # 假设16GB内存
                    'used': random.randint(4, 12),
                    'usage': random.randint(25, 75),
                    'freq': 3200
                }
            }
        
        # 更新界面
        self.update_hardware_data(hardware_data)
    
    def update_hardware_data(self, hardware_data):
        """更新硬件数据"""
        # 更新信息面板
        self.info_panel.update_hardware_data(hardware_data)
        
        # 更新仪表盘
        self.cpu_gauge.set_value(hardware_data.get('cpu', {}).get('usage', 0))
        self.igpu_gauge.set_value(hardware_data.get('igpu', {}).get('usage', 0))
        self.dgpu_gauge.set_value(hardware_data.get('dgpu', {}).get('usage', 0))